package cn.pinming.web;

import cn.pinming.common.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>TODO</p>
 *
 * @author wuwanggao@souche.com
 * @version 1.0
 */
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @GetMapping(value = "/index")
    public String index() {
        return "login";
    }

    @ResponseBody
    @PostMapping(value = "/signIn")
    public ServerResponse submitLogin(String username, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (Exception e) {
            log.error("登录失败，用户名[{}]", username, e);
            token.clear();
            ServerResponse.createByErrorMessage(e.getMessage());
        }
        return ServerResponse.createBySuccess();
    }


}
